<template>
    <div id="silder-left">
        <div class="list-left" :style="{ height: leftHeight, width: leftWidth }">
            <div class="list-heard">
                <!-- 插槽 标题参数 -->
                <slot name="ltitle"></slot>
            </div>
            <div class="list-left-div">
                <yh-input :placeholder="placeholders" :value="leftInput" style="width: calc(100% - 30px)" @input="onchaninput" size="mini"></yh-input>
                <el-button class="left-p" type="primary" icon="el-icon-search" @click="submitInput"> </el-button>
            </div>
            <!-- 证券加一个下拉框插槽 -->
            <div class="list-left-div" v-if="selectData">
                维度类别：<el-select v-model="selectedData" @change="handleSelectChange" filterable size="mini" style="width: 120px">
                    <el-option v-for="(i, key) in selectData" :key="key" :label="i.dictKeyName" :value="i.dictKey"> </el-option>
                </el-select>
            </div>
            <div class="left-tree" v-show="treeData">
                <el-tree
                    :data="treeData"
                    class="filter-tree"
                    node-key="groupId"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    @node-click="handleNodeClick"
                    :default-expanded-keys="defaultExpandedKeys"
                    :current-node-key="currentKey"
                    highlight-current
                    ref="tree"
                    :key="treeKey"
                    :lazy="!leftInputReal"
                    :load="loadNode"
                    v-loading="treeLoading"
                >
                    <!-- :default-checked-keys="defaultCheckedKeys" -->
                    <span slot-scope="{ node }">
                        <!-- 本地 -->
                        <span v-if="node.data.sourceType == '1'">
                            <span v-if="node.level < 2" :title="node.label">{{ node.label }}</span>
                            <span v-else :title="node.label">{{ node.data.stGrCode + '-' + node.label }}</span>
                        </span>
                        <!-- 外部 -->
                        <span v-else>
                            <span v-if="node.level < 2 || node.data.stGroupNodeType == 'NO_FUND'" :title="node.label">{{ node.label }}</span>
                            <span v-else>
                                <span v-if="node.data.stGroupNodeType == 'FUND'" :title="node.label">{{
                                    node.data.fundCode + '-' + node.label
                                }}</span>
                                <span v-else>
                                    <!-- // 指数、板块 取 风格库代码（A.C_ST_GR_CODE）[stGrCode] -->
                                    <!-- // 行业、按市价分、天相行业、非互斥维度、禁止质押库、申万行业  社保行业   取恒生维度编码 （A.C_HS_TRADE_NO）[hsTradeNo] -->
                                    <span v-if="['1', 'A', 'B', 'C', 'E', 'F', '2'].includes(node.data.tradeType)" :title="node.label">
                                        {{ (node.data.hsTradeNo || node.data.stGrCode) + '-' + node.label }}</span
                                    >
                                    <span v-else :title="node.label">{{
                                        node.data.stGrCode !== '-1' && node.data.stGroupNodeType !== 'DIMENSION_LAYER'
                                            ? node.data.stGrCode + '-' + node.label
                                            : node.label
                                    }}</span>
                                </span>
                                <!-- <span v-else :title="node.label">{{
                                    node.data.stGrCode !== '-1' ? node.data.stGrCode + '-' + node.label : node.label
                                }}</span> -->
                            </span>
                        </span>
                    </span>
                </el-tree>
            </div>
            <!-- 内容插槽 -->
            <slot></slot>
        </div>
        <div class="move-btn" v-move-crosswise></div>
    </div>
</template>
<script lang="ts">
import { Component, Emit, Model, Prop, Vue, Watch } from 'vue-property-decorator';

@Component({
    name: 'RiskLeftStockPool',
})
export default class RiskLeftStockPool extends Vue {
    currentNode: any = {};
    leftInputReal: string = '';
    // 定义按钮给父组件使用
    // @Emit('on-submit')
    private submitInput(): void {
        this.leftInputReal = this.leftInput;
        if (this.leftInputReal) {
            this.getStockPoolTree();
        }
        this.treeKey++;
    }

    // 定义输入框传值
    @Model('changeUserName', { type: String })
    leftInput!: string;

    // 输入框的值
    @Emit('changeUserName')
    private onchaninput(e: any) {
        // let filtration = this.$refs.tree as { filter?: any };
        // filtration.filter(e);
    }

    // 输入框提示
    @Prop({ default: '请输入' }) placeholders!: string;

    @Prop({ default: false }) loading!: boolean;

    // 总高度
    @Prop() leftHeight!: string;

    // 总宽度
    @Prop() leftWidth!: string;

    // tree的数据
    // @Prop() treeData!: any;

    // select的数据
    @Prop() selectData!: any;

    // 默认展开项
    @Prop() defaultExpandedKeys: any[];

    // // 默认选中项
    // @Prop() defaultCheckedKeys: any[];

    // 默认选中项
    @Prop() currentKey: string;

    // 默认唯一键
    @Prop({ default: 'groupId' }) readonly nodeKey!: string;

    private treeData: any = [];

    private selectedData = '';

    private defaultProps = {
        children: 'childGroup',
        label: 'stGrName',
        isLeaf: (data, node) => {
            if (!data.childGroupCount && data.stGrName !== '全公司' && data.stGroupNodeType !== 'DIMENSION_LAYER') {
                // 根据需要进行条件判断添加is-leaf类名
                return true;
            }
        },
        // isLeaf: 'childGroupCount',
        // id: 'stGrCode';
    };

    private treeKey: number = 0;
    private treeLoading: boolean = false; // 树加载

    // 查询所有证券池(基础树)
    getStockPoolTree() {
        this.treeLoading = true;
        return new Promise(resolve => {
            this.$axios
                .post('/stockPool/stGroup/tree', {
                    keyword: this.leftInput,
                    tradeType: this.selectedData,
                })
                .then((res: any) => {
                    resolve(res);
                    this.treeData = res;
                    this.treeLoading = false;
                    // console.log(res, 'res');
                })
                .catch(() => {
                    this.treeLoading = false;
                });
        });
    }

    // 维度类别变化事件
    handleSelectChange(val) {
        this.treeKey++;
    }

    loadNode(node, resolve) {
        console.log('loadNode');
        // 如果展开第一级节点，从后台加载一级节点列表
        if (node.level == 0) {
            this.loadfirstnode(resolve);
        }
        if (node.level == 1) {
            this.loadSecondnode(node, resolve);
        }
        // 如果展开其他级节点，动态从后台加载下一级节点列表
        if (node.level >= 2) {
            if (node.level == 2) {
                this.loadThirdnode(node, resolve);
            } else {
                this.loadchildnode(node, resolve);
            }
        }
    }

    // 加载第一级节点
    async loadfirstnode(resolve) {
        let params = {
            level: 0,
        };
        const res: any = await this.getStockPoolTree();
        return resolve(res);
    }

    // 加载第二级节点
    async loadSecondnode(node, resolve) {
        let params = {
            level: 0,
        };
        let data;
        if (node.data.stGrName == '外部') {
            data = this.treeData[1].childGroup;
        } else if (node.data.stGrName == '本地') {
            data = this.treeData[0].childGroup;
        }
        return resolve(data);
    }

    // 加载第三级节点
    async loadThirdnode(node, resolve) {
        let params = {
            level: 0,
        };
        let data;
        if (node.data.stGrName == '全公司') {
            data = this.treeData[1].childGroup[0].childGroup;
            data.forEach(ele => {
                if (ele.stGroupNodeType == 'POOL_TYPE') {
                    ele.stGrName = ele.stGrName + '(' + ele.stockCount + ')';
                }
            });
        } else if (node.data.stGroupNodeType == 'DIMENSION_LAYER') {
            console.log(node.data, 'DIMENSION_LAYER');

            data = node.data.childGroup;
        } else {
            data = await this.getChildNode(node.data);
        }
        return resolve(data);
    }

    // 加载节点的子节点集合
    async loadchildnode(node, resolve) {
        let params = {
            id: node.key,
        };
        let res: any;
        if (node.data.childGroupCount) {
            res = await this.getChildNode(node.data);
        } else {
            res = [];
        }
        return resolve(res);
    }

    // 根据父节点获取子节点
    getChildNode(nodeObj: any) {
        let param: any = {
            fundCode: '',
            stGrCode: '',
        };
        // let key: string = 'groupId';
        // 当节点类型为FUND时传fundCode查下级 优先级1 不用管childGroupCount是否为0
        if (nodeObj.stGroupNodeType == 'FUND') {
            param.fundCode = nodeObj.fundCode;
        } else {
            if (!nodeObj.childGroupCount) return;
            if (nodeObj.stGroupNodeType == 'POOL') {
                param.stGrCode = nodeObj.stGrCode;
            }
        }
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/stockPool/stGroup/node', param)
                .then((res: any) => {
                    res.forEach(ele => {
                        if (ele.stGroupNodeType == 'POOL_TYPE') {
                            ele.stGrName = ele.stGrName + '(' + ele.stockCount + ')';
                        }
                    });
                    // this.createTree(this.treeData, key, nodeObj[key], res);
                    // this.treeKey++;
                    resolve(res);
                })

                .catch(err => {
                    reject(err);
                });
        });
    }

    // tree按钮事件
    @Emit('on-handleNode')
    public handleNodeClick(data: any, node: any): any {
        this.currentNode = data;
        // if (!['LOCAL', 'EXTERNAL'].includes(data.stGroupNodeType)) {
        //     this.getChildNode(data);
        // }
        console.log(data, node, 'data');
    }
}
</script>
<style lang="scss" scoped>
.list-left {
    height: 100vh;
    border: 1px solid #cacaca;

    .list-heard {
        width: 100%;
        height: 34px;
        background: #e5e8eb;
        border: 1px solid #cacaca;
        padding-left: 10px;
        line-height: 34px;
        color: #222;
    }

    .list-left-div {
        height: 40px;
        background: #fff;
        border: 1px solid #cacaca;
        padding-top: 4px;
        padding-left: 10px;
        position: relative;

        .left-p {
            position: absolute;
            right: 5px;
            top: 4px;

            .el-icon-search {
                color: #fff;
            }
        }

        & /deep/ .el-button {
            padding: 6px;
        }
    }

    .left-tree {
        height: calc(100vh - 120px);
        overflow: scroll;
    }
}
</style>
